package com.example.roleplay.service.impl;

import com.example.roleplay.service.WebSearchService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 基于阿里云DashScope MCP WebSearch的搜索服务实现
 */
@Service
@ConditionalOnProperty(name = "roleplay.dashscope.mcp.enabled", havingValue = "true", matchIfMissing = true)
public class DashScopeWebSearchServiceImpl implements WebSearchService {
    
    private static final Logger logger = LoggerFactory.getLogger(DashScopeWebSearchServiceImpl.class);
    
    @Value("${roleplay.dashscope.api-key}")
    private String apiKey;
    
    @Value("${roleplay.dashscope.mcp.base-url}")
    private String baseUrl;
    
    @Value("${roleplay.dashscope.mcp.timeout:30s}")
    private String timeout;
    
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    
    // 需要网络搜索的关键词模式
    private static final List<Pattern> SEARCH_PATTERNS = Arrays.asList(
            Pattern.compile(".*最新.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*今天.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*现在.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*当前.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*天气.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*新闻.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*价格.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*股价.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*实时.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*最近.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*hot.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*latest.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*news.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*current.*", Pattern.CASE_INSENSITIVE),
            Pattern.compile(".*weather.*", Pattern.CASE_INSENSITIVE)
    );
    
    public DashScopeWebSearchServiceImpl() {
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
    }
    
    @Override
    public List<SearchResult> search(String query, int maxResults) {
        logger.info("执行DashScope网络搜索，查询：{}，最大结果数：{}", query, maxResults);
        
        try {
            // 构建请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            headers.set("Accept", "text/event-stream");
            
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("messages", Arrays.asList(
                Map.of("role", "user", "content", query)
            ));
            requestBody.put("stream", true);
            requestBody.put("parameters", Map.of(
                "max_results", maxResults,
                "search_query", query
            ));
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    baseUrl,
                    HttpMethod.POST,
                    entity,
                    String.class
            );
            
            if (response.getStatusCode() == HttpStatus.OK) {
                return parseSSEResponse(response.getBody());
            } else {
                logger.warn("搜索请求失败，状态码：{}", response.getStatusCode());
                return Collections.emptyList();
            }
            
        } catch (Exception e) {
            logger.error("执行网络搜索时发生错误", e);
            return Collections.emptyList();
        }
    }
    
    @Override
    public boolean shouldSearch(String query) {
        if (query == null || query.trim().isEmpty()) {
            return false;
        }
        
        String normalizedQuery = query.trim();
        
        // 检查是否匹配搜索模式
        boolean matches = SEARCH_PATTERNS.stream()
                .anyMatch(pattern -> pattern.matcher(normalizedQuery).matches());
        
        logger.debug("查询 '{}' 是否需要网络搜索: {}", query, matches);
        return matches;
    }
    
    /**
     * 解析SSE响应数据
     */
    private List<SearchResult> parseSSEResponse(String sseData) {
        List<SearchResult> results = new ArrayList<>();
        
        if (sseData == null || sseData.trim().isEmpty()) {
            return results;
        }
        
        try {
            // 按行分割SSE数据
            String[] lines = sseData.split("\\n");
            
            for (String line : lines) {
                if (line.startsWith("data: ")) {
                    String jsonData = line.substring(6).trim();
                    
                    // 跳过特殊标记
                    if ("[DONE]".equals(jsonData) || jsonData.isEmpty()) {
                        continue;
                    }
                    
                    try {
                        JsonNode jsonNode = objectMapper.readTree(jsonData);
                        
                        // 解析搜索结果
                        if (jsonNode.has("choices")) {
                            JsonNode choices = jsonNode.get("choices");
                            if (choices.isArray() && choices.size() > 0) {
                                JsonNode choice = choices.get(0);
                                if (choice.has("delta") && choice.get("delta").has("content")) {
                                    String content = choice.get("delta").get("content").asText();
                                    
                                    // 尝试从内容中提取搜索结果
                                    SearchResult result = extractSearchResult(content);
                                    if (result != null) {
                                        results.add(result);
                                    }
                                }
                            }
                        }
                        
                        // 解析工具调用结果
                        if (jsonNode.has("tool_calls")) {
                            JsonNode toolCalls = jsonNode.get("tool_calls");
                            for (JsonNode toolCall : toolCalls) {
                                if (toolCall.has("function") && toolCall.get("function").has("arguments")) {
                                    String arguments = toolCall.get("function").get("arguments").asText();
                                    List<SearchResult> toolResults = parseToolCallResults(arguments);
                                    results.addAll(toolResults);
                                }
                            }
                        }
                        
                    } catch (JsonProcessingException e) {
                        logger.debug("解析JSON数据失败: {}", jsonData, e);
                    }
                }
            }
            
            logger.info("解析SSE响应完成，获得{}个搜索结果", results.size());
            
        } catch (Exception e) {
            logger.error("解析SSE响应时发生错误", e);
        }
        
        return results;
    }
    
    /**
     * 从内容中提取搜索结果
     */
    private SearchResult extractSearchResult(String content) {
        // 这里可以根据实际返回的内容格式进行解析
        // 由于不确定具体格式，先简单处理
        if (content != null && !content.trim().isEmpty()) {
            return new SearchResult(
                    "搜索结果",
                    content.trim(),
                    "",
                    "DashScope WebSearch"
            );
        }
        return null;
    }
    
    /**
     * 解析工具调用结果
     */
    private List<SearchResult> parseToolCallResults(String arguments) {
        List<SearchResult> results = new ArrayList<>();
        
        try {
            JsonNode argsNode = objectMapper.readTree(arguments);
            
            if (argsNode.has("results")) {
                JsonNode resultsArray = argsNode.get("results");
                
                if (resultsArray.isArray()) {
                    for (JsonNode resultNode : resultsArray) {
                        String title = resultNode.has("title") ? resultNode.get("title").asText() : "";
                        String content = resultNode.has("content") ? resultNode.get("content").asText() : "";
                        String url = resultNode.has("url") ? resultNode.get("url").asText() : "";
                        String source = resultNode.has("source") ? resultNode.get("source").asText() : "DashScope WebSearch";
                        
                        results.add(new SearchResult(title, content, url, source));
                    }
                }
            }
            
        } catch (JsonProcessingException e) {
            logger.debug("解析工具调用参数失败: {}", arguments, e);
        }
        
        return results;
    }
}